// var request = require('request');
var moment = require('moment');
const appId = 'wxbc675391baa7ae28';
const appSecret = 'c9dc72fc2d2162fb7f8e65b97f1c3d5a';
let co = require("co");
let request = require("co-request");


module.exports = {

  //获取公众号access_token
  getToken: function (call) {
    Token.find({type: 'access_token'}).then(function (record) {
      var oriToken = record[0].value;
      var tokenUpdateTime = Number(record[0].createTime);
      var now = Number(moment().format('x'));
      if (now - tokenUpdateTime < 7000) {
        return call(oriToken);
      } else {
        request('wechat url', function (err, resp, body) {
          if (err) return err;
          var tokenUpdated = JSON.parse(body).access_token;
          Token.update({type: 'access_token'}, {value: tokenUpdated, createTime: now}).then(function (result) {
            console.log('update access_token', result);
            return call(tokenUpdated);
          }).catch(function (err) {
            return err;
          })
        })
      }
    })
  },

  getApiToken: function *() {
    // request.post('http://localhost:5584/gettoken', {form:{username: 'admin', password: 'Sang900404'}}, function (err, resp, body) {
    //   if (err) return call(err);
    //   console.log('token:',body);
    //   return call(body);
    // })
    let result = yield request.post('http://www.auewecanberra.com:4567/gettoken', {form:{username: 'admin', password: 'Sang900404'}})
    return result;
  },

  getApiTokenCall: function (call) {
    request.post('http://wms.auewecanberra.com/gettoken', {form:{username: 'admin', password: 'Sang900404'}}, function (err, resp, body) {
      if (err) return call(err);
      console.log('token:',body);
      return call(body);
    })
  },

  getTokenSync: function () {
    return new Promise(function (resolve, reject) {
      request.post('http://wms.auewecanberra.com/gettoken', {form:{username: 'admin', password: 'Sang900404'}}, function (err, resp, body) {
        if (err) reject(err);

      })
    })
  },

  getWechatToken: function (call) {
    request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appId+'&secret='+appSecret, function (err, resp, body) {
      if (err) return call(err);
      return call(JSON.parse(body).access_token);
    })
  }
}
